﻿using Admin.IdentityServer.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Admin.IdentityServer.Data
{
    public class ApplicationDbContextSeed
    {
        private UserManager<ApplicationUser> _userManager;
        private RoleManager<ApplicationRole> _roleManager;

        public async Task SeedAsync(ApplicationDbContext context, IServiceProvider services)
        {
            if (!context.Roles.Any())
            {
                var role = new ApplicationRole()
                {
                    Name = "Administrators",
                    NormalizedName = "Administrators"
                };
                _roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
                var result = await _roleManager.CreateAsync(role);
                if (!result.Succeeded)
                {
                    throw new Exception("初始默认角色失败:" + result.Errors.SelectMany(e => e.Description));
                }
            }

            if (!context.Users.Any())
            {
                _userManager = services.GetRequiredService<UserManager<ApplicationUser>>();

                var defaultUser = new ApplicationUser
                {
                    UserName = "Administrator",
                    Email = "lxd_8023@qq.com",
                    NormalizedUserName = "admin",
                    SecurityStamp = "admin",
                    Avatar = "https://baike.baidu.com/pic/%E5%BE%AE%E8%BD%AF/124767/0/2f738bd4b31c870124df02182e7f9e2f0608ffe7?fr=lemma&ct=single#aid=0&pic=2f738bd4b31c870124df02182e7f9e2f0608ffe7"
                };


                var result = await _userManager.CreateAsync(defaultUser, "Password$123");
                await _userManager.AddToRoleAsync(defaultUser, "Administrators");



                if (!result.Succeeded)
                {
                    throw new Exception("初始默认用户失败:" + result.Errors.SelectMany(e => e.Description));
                }
            }
        }
    }
}
